import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:path/path.dart';
import 'package:photo_frame/net/model/asset_trans_model.dart';
import 'package:photo_frame/net/model/asset_trans_record_model.dart';
import 'package:photo_frame/pages/gallery/send_asset/widget/send_asset_item_widget.dart';
import 'package:photo_frame/pages/gallery/send_asset/widget/send_asset_record_widget.dart';
import 'package:photo_frame/provider/app_trans_asset_provider.dart';
import 'package:photo_frame/router/router_context.dart';
import 'package:photo_frame/utils/app_const.dart';
import 'package:photo_frame/utils/localization_util.dart';
import 'package:photo_frame/widgets/app_bar_widget.dart';
import 'package:provider/provider.dart';

class SendAssetRecordPage extends StatefulWidget {
  @override
  State<SendAssetRecordPage> createState() => _SendAssetRecordPageState();
}

class _SendAssetRecordPageState extends State<SendAssetRecordPage> {
  SendAssetPrvider provider = SendAssetPrvider();

  @override
  void initState() {
    super.initState();
    provider.fetchListData();
  }

  @override
  void dispose() {
    provider.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color(0xfff2f2f2),
        appBar:
            commonAppBar(appLocalForContext(context).sendRecord, onBack: () {
          ARouter.instance.pagePopToRoot();
        }, actions: [buildRightNavbarItem()]),
        body: ChangeNotifierProvider.value(
            value: provider,
            builder: (context, provider) {
              return SafeArea(
                child: Container(
                  color: Color(0xfff2f2f2),
                  width: double.infinity,
                  child: Column(
                    children: [
                      Expanded(child: Consumer<SendAssetPrvider>(
                        builder: (context, provider, child) {
                          bool isEmpty = provider.isEmpty();
                          final itemCount = isEmpty ? 1 : provider.itemCount();
                          return ListView.builder(
                              itemBuilder: (context, index) {
                                if (isEmpty) {
                                  return provider.buildEmptyItem(context);
                                } else {
                                  return provider.buidleItem(index);
                                }
                              },
                              itemCount: itemCount);
                        },
                      ))
                    ],
                  ),
                ),
              );
            }));
  }

  buildRightNavbarItem() {
    return CupertinoButton(
      padding: EdgeInsets.zero,
      onPressed: () {
        EasyLoading.showToast(appLocal().clearSendRecordSuccess);
        AppAssetTransProvider.provider().deleteAllTransModels();
      },
      child: actionTextWidget(appLocal().clearRecord),
    );
  }
}

class SendAssetPrvider extends ChangeNotifier {
  List<AssetTransModel> transAssetList = [];
  List<AssetTransRecordModel> recordList = [];

  SendAssetPrvider() {
    AppAssetTransProvider.provider().addListener(dataSoureChanged);
  }

  @override
  void dispose() {
    AppAssetTransProvider.provider().removeListener(dataSoureChanged);
    super.dispose();
  }

  dataSoureChanged() {
    processListData();
  }

  fetchListData() async {
    transAssetList.clear();
    recordList.clear();
    await AppAssetTransProvider.provider().inpectAssetTransStatus();
    processListData();
  }

  processListData() {
    List<AssetTransModel> list = AppAssetTransProvider.provider().allData;
    transAssetList.clear();
    recordList.clear();
    Map<String, AssetTransRecordModel> recordMap = {};
    for (var transModel in list) {
      if (transModel.batchId == null) continue;
      if (transModel.transStatus == 1) {
        if (recordMap[transModel.batchId] == null) {
          AssetTransRecordModel record = AssetTransRecordModel();
          record.transDate = transModel.transDate;
          record.transAssetList.add(transModel);
          recordMap[transModel.batchId!] = record;
        } else {
          recordMap[transModel.batchId]!.transAssetList.add(transModel);
        }
      } else {
        transAssetList.add(transModel);
      }
    }
    transAssetList.sort((a, b) {
      return int.parse(b.transDate ??
          DateTime.timestamp().millisecondsSinceEpoch.toString()) -
          int.parse(a.transDate ??
              DateTime.timestamp().millisecondsSinceEpoch.toString());
    });
    recordList.addAll(recordMap.values);
    recordList.sort((a, b) {
      return int.parse(b.transDate ??
              DateTime.timestamp().millisecondsSinceEpoch.toString()) -
          int.parse(a.transDate ??
              DateTime.timestamp().millisecondsSinceEpoch.toString());
    });
    notifyListeners();
  }

  bool isEmpty() {
    return transAssetList.isEmpty && recordList.isEmpty;
  }

  int itemCount() {
    return transAssetItemCount() + recordItemCount();
  }

  int transAssetItemCount() {
    int count = 0;
    if (transAssetList.isNotEmpty) {
      count = transAssetList.length + 1;
    }
    return count;
  }

  int recordItemCount() {
    int count = 0;
    if (recordList.isNotEmpty) {
      count = recordList.length + 1;
    }
    return count;
  }

  buidleItem(int index) {
    if (index < transAssetItemCount()) {
      return buildTransAssetItem(index);
    } else {
      return buildRecordItem(index - transAssetItemCount());
    }
  }

  buildEmptyItem(BuildContext context) {
    final height = MediaQuery.of(context).size.height;
    return Container(
      width: double.infinity,
      height: height - 200,
      child: Center(
        child: Container(
          width: 124,
          child: Column(children: [
            SizedBox(height: height / 2.0 - 200),
            Image.asset("images/pic_send_record_empty.png",
                width: 124, height: 124),
            SizedBox(height: 20),
            Text(
              appLocal().sendRecordIsEmpty,
              style: TextStyle(fontSize: 13, color: Color(0xff666666)),
            )
          ]),
        ),
      ),
    );
  }

  buildTransAssetItem(int index) {
    if (index == 0) {
      return Padding(
        padding: EdgeInsets.only(top: 8, left: 10, bottom: 8),
        child: Text(
          appLocal().uploadingTitle,
          textAlign: TextAlign.left,
        ),
      );
    }
    return SendAssetItemWidget(
      transModel: transAssetList[index - 1],
      resend: (model) {
        AppAssetTransProvider.provider().reUpLoadAsset(model);
      },
      delete: (model) {
        AppAssetTransProvider.provider().deleteTransModel(model);
      },
    );
  }

  buildRecordItem(int index) {
    if (index == 0) {
      return Padding(
        padding: EdgeInsets.only(top: 8, left: 10, bottom: 8),
        child: Text(
          appLocal().sendHistoryTitle,
          textAlign: TextAlign.left,
        ),
      );
    }
    AssetTransRecordModel recordModel = recordList[index - 1];
    return SendAssetRecordWidget(
      recordModel: recordModel,
      resend: (model) {
        List<String> assetIds =
            recordModel.transAssetList.map((t) => t.assetId ?? "").toList();
        AppAssetTransProvider.provider()
            .updateTransAssetBuffer("assetIds", assetIds);
        ARouter.instance.pagePopToRootThenPush("/selectFrame",
            arguments: {"source": SelectFrameSource.GALLERY});
      },
      delete: (model) {
        if (recordModel.transAssetList.isNotEmpty) {
          AppAssetTransProvider.provider().batchDeleteTransModels(
              recordModel.transAssetList.first.batchId ?? "");
        }
      },
    );
  }
}
